package itbour.onetouchshow.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.google.gson.Gson;
import com.lsjr.callback.DownloadSubscriber;
import com.lsjr.utils.HttpUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.bean.FreeCreateOrigin;
import itbour.onetouchshow.bean.PersonalCreateConfigBean;
import itbour.onetouchshow.bean.TransitionsBean;
import itbour.onetouchshow.bean.TurnTransitions;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;

/**
 * Created by Administrator on 2018/6/22.
 */

public class AssetsDataUtils {

    private static PersonalCreateConfigBean mCustomVideoConfigure;

    /**
     * 得到json文件中的内容
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static PersonalCreateConfigBean getCustomVideoConfigure() {
        String data = PreferencesHelper.getData(AppConst.KEY_PERSONAL_CREATE_CONFIG);
        mCustomVideoConfigure = new Gson().fromJson(data, PersonalCreateConfigBean.class);
        return mCustomVideoConfigure;
        // return mCustomVideoConfigure;
    }

    public static void setCustomVideoConfigure(PersonalCreateConfigBean mCustomVideoConfigure) {
        AssetsDataUtils.mCustomVideoConfigure = mCustomVideoConfigure;
    }

    /**
     * 将字符串转换为 对象
     *
     * @param json
     * @param type
     * @return
     */
    public static <T> T JsonToObject(String json, Class<T> type) {
        Gson gson = new Gson();
        return gson.fromJson(json, type);
    }

    public static String[] videoWHDA(String videoUrl) {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            metadataRetriever.setDataSource(videoUrl, new HashMap());
        } else {
            metadataRetriever.setDataSource(videoUrl);
        }
        String width = metadataRetriever.extractMetadata(18);
        String height = metadataRetriever.extractMetadata(19);
        String duration = metadataRetriever.extractMetadata(9);
        //duration = String.valueOf(Double.valueOf(duration).doubleValue() / 1000.0D);
        String angle = metadataRetriever.extractMetadata(24);
        L_.e("width width 角度：" + width);
        L_.e("width height 角度：" + height);
        L_.e("width angle角度：" + angle);
        if (angle.equals("90") || angle.equals("270")) {
            String tempWidth = width;
            width = height;
            height = tempWidth;
        }

        metadataRetriever.release();
        return new String[]{width, height, duration, angle};
    }

    public static int[] getVideoWHDA(String videoUrl) {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            metadataRetriever.setDataSource(videoUrl, new HashMap());
        } else {
            metadataRetriever.setDataSource(videoUrl);
        }
        String width = metadataRetriever.extractMetadata(18);
        String height = metadataRetriever.extractMetadata(19);
        String duration = metadataRetriever.extractMetadata(9);
        //得到秒
        int d = TypeCastHelper.toInt(duration) / 1000;
        String angle = metadataRetriever.extractMetadata(24);
        L_.e("width width 角度：" + width);
        L_.e("width height 角度：" + height);
        L_.e("width angle角度：" + angle);
        if (angle.equals("90") || angle.equals("270")) {
            String tempWidth = width;
            width = height;
            height = tempWidth;
        }
        metadataRetriever.release();
        return new int[]{TypeCastHelper.toInt(width), TypeCastHelper.toInt(height), d, TypeCastHelper.toInt(angle)};
    }


    public static double getVideoDuration(String videoUrl) {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            metadataRetriever.setDataSource(videoUrl, new HashMap());
        } else {
            metadataRetriever.setDataSource(videoUrl);
        }
        String durationStr = metadataRetriever.extractMetadata(9);
        //得到秒
        double duration = stringToDouble(durationStr);
        metadataRetriever.release();
        return duration;
    }

    /**
     * String转换成double 保留N位小数。
     *
     * @param a
     * @return
     */
    public static double stringToDouble(String a) {
        double b = Double.valueOf(a) / 1000.0;
        DecimalFormat df = new DecimalFormat("#.0");//此为保留1位小数，若想保留2位小数，则填写#.00  ，以此类推
        String temp = df.format(b);
        b = Double.valueOf(temp);
        return b;
    }


    public static FreeCreateOrigin getFreeCreateOrigin(Context context) {
        //得到本地json文本内容
        String fileName = "FreeCreateOrigin.json";
        String foodJson = AssetsDataUtils.getJson(context, fileName);
        return new Gson().fromJson(foodJson, FreeCreateOrigin.class);
    }

    public static TurnTransitions getTurnTransition(Context context) {
        //得到本地json文本内容
        String fileName = "transitions.json";
        String foodJson = AssetsDataUtils.getJson(context, fileName);
        return new Gson().fromJson(foodJson, TurnTransitions.class);
    }


    public static FreeCreateOrigin.MainAssetsBean creatMoudle(List<FreeCreateOrigin.MainAssetsBean> videoBeans,
                                                              List<TransitionsBean> transitions) {
        //FreeCreateOrigin freeCreateOrigin = getFreeCreateOrigin(context);
        // List<FreeCreateOrigin.MainAssetsBean> videoBeans = freeCreateOrigin.getMainAssets();
        FreeCreateOrigin.MainAssetsBean mainAssetsBean = null;
        FreeCreateOrigin.MainAssetsBean newMainAssetsBean;
        if (videoBeans != null && videoBeans.size() > 0) {
            mainAssetsBean = videoBeans.get(videoBeans.size() - 1);
        }
        if (transitions == null) {
            newMainAssetsBean = new FreeCreateOrigin.MainAssetsBean();
            //newMainAssetsBean.setId(mainAssetsBean.getId() + 1);
            newMainAssetsBean.setId(videoBeans.size() + 1);
            // addTransition(transitions);
        } else {
            newMainAssetsBean = new FreeCreateOrigin.MainAssetsBean();
            //newMainAssetsBean.setId(mainAssetsBean.getId() + 1);
            newMainAssetsBean.setId(transitions.size() + 2);
            addTransition(null, transitions, videoBeans);
        }
        //videoBeans.add(mainAssetsBean);
        return newMainAssetsBean;
    }


    public static FreeCreateOrigin.MainAssetsBean creatMainAssetsBeanMoudle(FreeCreateOrigin freeCreateOrigin, List<FreeCreateOrigin.MainAssetsBean> videoBeans,
                                                                            List<TransitionsBean> transitions, String videoUrl) {
        //FreeCreateOrigin freeCreateOrigin = getFreeCreateOrigin(context);
        // List<FreeCreateOrigin.MainAssetsBean> videoBeans = freeCreateOrigin.getMainAssets();
        FreeCreateOrigin.MainAssetsBean newMainAssetsBean = new FreeCreateOrigin.MainAssetsBean();
        //newMainAssetsBean.setId(mainAssetsBean.getId() + 1);
        newMainAssetsBean.setId(videoBeans.size() + 1);
        // newMainAssetsBean.setCoverImage("http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U20/2018/07/191/165753661_mvc8KGotZCDZZGCWFeTZ.jpg");
        newMainAssetsBean.setUrl(videoUrl);
        newMainAssetsBean.setProcessedUrl(videoUrl);
        newMainAssetsBean.setStart(freeCreateOrigin.getDuration());
        newMainAssetsBean.setCt(1403);
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            metadataRetriever.setDataSource(videoUrl, new HashMap());
        } else {
            metadataRetriever.setDataSource(videoUrl);
        }
        String width = metadataRetriever.extractMetadata(18);
        String height = metadataRetriever.extractMetadata(19);
        String durationStr = metadataRetriever.extractMetadata(9);
        //得到秒
        double startduration = TypeCastHelper.toDouble(durationStr);
        double duration = (startduration / 10.0 / 10.0 / 10);
        String angle = metadataRetriever.extractMetadata(24);
        L_.e("width width 角度：" + width);
        L_.e("width height 角度：" + height);
        L_.e("width angle角度：" + angle);
        metadataRetriever.release();
        newMainAssetsBean.setW(TypeCastHelper.toInt(width));
        newMainAssetsBean.setH(TypeCastHelper.toInt(height));
        newMainAssetsBean.setDuration(duration);
        newMainAssetsBean.setAn(TypeCastHelper.toInt(angle));
        freeCreateOrigin.setDuration(Math.round(freeCreateOrigin.getDuration() + duration));
        videoBeans.add(newMainAssetsBean);
        addTransition(freeCreateOrigin, transitions, videoBeans);
        return newMainAssetsBean;
    }


    public static synchronized List<FreeCreateOrigin.MainAssetsBean> removeOneMainAssetsBeanMoudle(FreeCreateOrigin freeCreateOrigin, List<FreeCreateOrigin.MainAssetsBean> videoBeans, List<TransitionsBean> transitions, int videoId) {
        int index = 0;
        for (int i = 0; i < videoBeans.size(); i++) {
            if (videoBeans.get(i).getId() == videoId) {
                index = i;
                videoBeans.remove(i);
            }
        }
        freeCreateOrigin.setMainAssets(videoBeans);
        removeTransition(freeCreateOrigin, transitions, videoBeans, index);
        return videoBeans;
    }


    /**
     * 删除一个转场
     */
    public static void removeTransition(FreeCreateOrigin freeCreateOrigin, List<TransitionsBean> transitions, List<FreeCreateOrigin.MainAssetsBean> videoBeans, int index) {
        if (videoBeans.size() > 2) {
            if (index == 0) {
                transitions.remove(0);
            } else {
                transitions.remove(index - 1);
            }
        } else {
            if (transitions != null && transitions.size() == 1) {
                transitions.remove(0);
            }
        }
        freeCreateOrigin.setTransition(transitions);
    }


    /**
     * 默认加转场节点
     */

    public static void addTransition(FreeCreateOrigin freeCreateOrigin, List<TransitionsBean> transitions, List<FreeCreateOrigin.MainAssetsBean> videoBeans) {
        TransitionsBean transitionBean;
        List<Integer> newassId;
        if (transitions != null && transitions.size() > 0) {
            transitionBean = transitions.get(transitions.size() - 1);
            List<Integer> assetid = transitionBean.getAssetid();
            newassId = new ArrayList<>();
            for (int i = 0; i < assetid.size(); i++) {
                newassId.add(assetid.get(i) + 1);
            }
        } else {
            //第一次添加
            //  transitionBean = new TransitionsBean();
            newassId = new ArrayList<>();
            newassId.add(1);
            newassId.add(2);
        }
        // transitionBean.setAssetid(newassId);
        TransitionsBean newTransitionBean = new TransitionsBean();
        newTransitionBean.setAssetid(newassId);
        if (videoBeans.size() - 1 == transitions.size()) {
            return;
        }
        //  newTransitionBean.setDuration(freeCreateOrigin.getDuration());
        transitions.add(newTransitionBean);
    }


    /**
     * 位置交换
     * //拿到当前拖拽到的item的viewHolder
     * 排序连续动画的两个视频ID 动画
     */
    public static void swapTransitions(List<FreeCreateOrigin.MainAssetsBean> videoBeans, List<TransitionsBean> transitions) {
        /**
         * 得到原来数据交换新Id 移到目标后面的所有连续ID都得+1 toPosition
         */
        for (int i = 0; i < transitions.size(); i++) {
            TransitionsBean transition = transitions.get(i);//0   12
            FreeCreateOrigin.MainAssetsBean mainAssetsBean = videoBeans.get(i);//0   12
            Integer startinteger = mainAssetsBean.getId();
            Integer endinteger = videoBeans.get(i + 1).getId();
            List<Integer> newid = new ArrayList<>();
            newid.add(startinteger);
            newid.add(endinteger);
            transition.setAssetid(newid);
        }
    }

    /**
     * 位置交换
     * //拿到当前拖拽到的item的viewHolder
     * 排序连续动画的两个视频ID 动画
     */
    public static void swapTransitions(List<TransitionsBean> transitions) {
        /**
         * 得到原来数据交换新Id
         */
        //移到目标后面的所有连续ID都得+1 toPosition
        for (int i = 0; i < transitions.size(); i++) {
            TransitionsBean transition = transitions.get(i);//0   12
            TransitionsBean mewTransition = null;
            if (i < transitions.size() - 1) {
                mewTransition = transitions.get(i + 1);//1   2 3
            } else {
                mewTransition = transitions.get(transitions.size() - 1);//1   2 3
            }
            if (mewTransition == null) break;
            List<Integer> assetid = transition.getAssetid();
            List<Integer> toAssetid = mewTransition.getAssetid();
            Integer startinteger = assetid.get(0);
            Integer endinteger = toAssetid.get(0);
            if (i == 0 && (transition.getAssetid().get(1) == transitions.size() + 1)) {
                //说明移到第一个来了
                {
                    startinteger = transition.getAssetid().get(1);
                }
            }

            if (i == transitions.size() - 1 && transition.getAssetid().get(0) == 1) {
                //说明移到最后一个
                {
                    startinteger = transitions.size() + 1;
                    endinteger = transition.getAssetid().get(0);
                }
                // startinteger = transitions.get(i - 1).getAssetid().get(1);
            }
            List<Integer> newid = new ArrayList<>();
            newid.add(startinteger);
            newid.add(endinteger);
            transition.setAssetid(newid);
        }
    }

    public static void swapTransitions(TransitionsBean transitionsBean, TransitionsBean transitionsBean1) {
        //替换了ID 后的新的
        transitionsBean.setAssetid(transitionsBean1.getAssetid());
        // transitionsBean1 = transitionsBean;
        transitionsBean1.setCt(transitionsBean.getCt());
        transitionsBean1.setDbId(transitionsBean.getDbId());
        transitionsBean1.setDuration(transitionsBean.getDuration());
        transitionsBean1.setIntersect(transitionsBean.getIntersect());
        transitionsBean1.setLayer(transitionsBean.getLayer());
        //transitionsBean1.setIcon(transitionsBean.getIcon());
        //transitionsBean1.setName(transitionsBean.getName());
    }

    public static void doDonwloadVideo(String url, DownLoadVideoListener loadVideoListener) {
        String name = DateUtils.getYMD() + FileUtils.getFileName(url);
        //先查找本地   必须保证在我们自己的目录下打开才能找到  如果自己发出相当于重新下载一次
        boolean downLoad = true;
        String path = Environment.getExternalStorageDirectory() + "/OneTouchShow";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (AppCache.getInstance().fileExists(path, name)) {
            downLoad = false;
        }
        if (downLoad) {
            L_.e("下载文件" + name);
            HttpUtils.getInstance().downloadFile(url, new DownloadSubscriber(UIUtils.getContext(),
                    null, name) {
                @Override
                public void onComplete(String path) {
                    // L_.e("文件保存路径：" + path);
                    // T_.showCustomToast("文件保存路径：" + path);
                    AlbumNotifyHelper.insertVideoToMediaStore(UIUtils.getContext(), String.valueOf(System.currentTimeMillis()), 0, 0);
                    if (loadVideoListener != null) {
                        loadVideoListener.onSuccess(path);
                    }
                }

                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    int progress = (int) (bytesRead * 100 / contentLength);
                    // L_.e(progress + "% ");
                }

                @Override
                protected void onXError(String exception) {
                    // L_.e(exception + "% ");
                    T_.showToastReal(exception);
                    if (loadVideoListener != null) {
                        loadVideoListener.onFail();
                    }
                }
            });
        } else {
            path = path + File.separator + name;
            path = path.replaceAll("//", "/");
            if (loadVideoListener != null) {
                loadVideoListener.onSuccess(path);
            }
        }

    }


    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    public static Boolean hideInputMethod(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return false;
    }


    public interface DownLoadVideoListener {
        void onSuccess(String path);

        void onFail();
    }


}
